<template>
  <a-button v-bind="$attrs" :class="customClass" :disabled="isStart" @click="handleStart" :loading="loading">
    {{ getButtonText }}
  </a-button>
</template>
<script lang="ts">
import { defineComponent, ref, watchEffect, computed, unref } from 'vue'
import { useCountdown } from './useCountdown'
import { isFunction } from '@/utils/is'

const props = {
  value: { type: [Object, Number, String, Array] },
  count: { type: Number, default: 60 },
  customClass: { type: String },
  beforeStartFunc: {
    type: Function as PropType<() => Promise<boolean> | boolean>,
    default: null
  }
}

export default defineComponent({
  name: 'CountButton',
  props,
  setup(props) {
    const loading = ref(false)

    const { currentCount, isStart, start, reset } = useCountdown(props.count)

    const getButtonText = computed(() => {
      return !unref(isStart) ? '获取验证码' : `${unref(currentCount)}秒后获取`
    })

    watchEffect(() => {
      props.value === undefined && reset()
    })

    async function handleStart() {
      const { beforeStartFunc } = props
      if (beforeStartFunc && isFunction(beforeStartFunc)) {
        loading.value = true
        try {
          const canStart = await beforeStartFunc()
          canStart && start()
        } finally {
          loading.value = false
        }
      } else {
        start()
      }
    }
    return { handleStart, currentCount, loading, getButtonText, isStart }
  }
})
</script>
<style lang="less" scoped>
.register-code {
  &.ant-btn {
    height: 48px;
    background: #2a64f6;
    border-color: #2a64f6;
    color: #fff;
    font-weight: 500;
    border-radius: 4px;
    &:hover {
      background: #4684f7;
      border-color: #4684f7;
    }
    &[disabled] {
      color: #fff;
      background: #cdcdcd;
      border-color: #cdcdcd;
    }
  }
}
</style>
